﻿<%@ WebHandler Language="C#" Class="trusthandler" %>

using System;
using System.Web;
using System.Data;
using Chenxin.Lib.Utility;
using System.Data.SqlClient;

public class trusthandler : AjaxHandlerBase {
    public trusthandler()
    {
        htTypePermit.Add("add", Constants.Permit_AddTrustAdd);
        htTypePermit.Add("edit", Constants.Permit_AddTrustEdit);
        htTypePermit.Add("del", Constants.Permit_AddTrustDel);
        htTypePermit.Add("cancel", Constants.Permit_AddTrustCel);
        htTypePermit.Add("uncancel", Constants.Permit_AddTrustUnCel);
    }
    
    public override void RequestProcess(HttpContext context)
    {
        context.Response.AddHeader("pragma", "no-cache");
        context.Response.AddHeader("cache-control", "");
        context.Response.CacheControl = "no-cache";
        
        string strop = context.Request["op"];
        
        string strResponse = "";
        switch (strop.ToLower())
        {
            case "add"://添加委托
                strResponse = AddEnTrustInfo(context);
                break;
            case "edit"://修改委托
                strResponse = EditEnTrustInfo(context);
                break;
            case "cancel"://作废委托
                strResponse = CancelEnTrustInfo(context);
                break;
            case "uncancel"://取消作废
                strResponse = UncancelEnTrustInfo(context);
                break;
            case "getmodel"://获取委托信息
                strResponse = GetEntrustModel(context);
                break;
            case "getlist"://获取委托列表
                strResponse = GetEntrustList(context);
                break;
            case "del"://删除委托
                strResponse = DelEnTrustInfo(context);
                break;
            case "existscode"://委托编号存在检查
                strResponse = ExistsCode(context);
                break;
            case "gettrustlist":
                strResponse = getHouseTrustList(context);
                break;
            default:
                break;
        }

        context.Response.Write(strResponse);
    }

    private string DelEnTrustInfo(HttpContext context)
    {
        try
        {
            if (context.Request["modelid"] != null)
            {
                Chenxin.Lib.House.Entity.House_EntrustInfo clhehe = Chenxin.Lib.House.DAL.House_EntrustInfo.GetModel(new Guid(context.Request["modelid"]));
                
                Chenxin.Lib.House.DAL.House_EntrustInfo.Delete(new Guid(context.Request["modelid"]));

                //添加用户操作日志 2010-5-11 王玮 Add
                AddLog("" + CurrentUserInfo.UserName + "删除了一个委托:[" + clhehe.HouseAddress + "]房源已删除委托。",
                        OperationType.OperationTypeComboList()["OprType_TrustDel"].ToString());
                
                return "{success:'1',msg:'删除成功！',data:''}";
            }
            else
            {
                return "{success:'0',msg:'请选择一条记录！',data:''}";
            }
        }
        catch (Exception e)
        {
            return string.Format("{{success:'0',msg:'{0}',data:''}}", e.Message);
        }
    }
    
    /// <summary>
    /// 获取委托列表；
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    private string GetEntrustList(HttpContext context)
    {
        try
        {
            int iPageIndex = (string.IsNullOrEmpty(context.Request["pageindex"])) ? 1 : int.Parse(context.Request["pageindex"]) + 1;//页码
            int iPageSize = (string.IsNullOrEmpty(context.Request["pagesize"])) ? 30 : int.Parse(context.Request["pagesize"]);//页记录数
            string strRegion = context.Request["region"];//区域；
            int iStatus = string.IsNullOrEmpty(context.Request["status"]) ? 1000 : int.Parse(context.Request["status"]);//委托状态 状态有效：0；无效：-1
            int iBussines = string.IsNullOrEmpty(context.Request["business"]) ? 1000 : int.Parse(context.Request["business"]);//委托交易类型 类型：20出租；10出售;30租售
            int iTrustType = 1000;//string.IsNullOrEmpty(context.Request["trusttype"]) ? 1000 : int.Parse(context.Request["trusttype"]);//委托方式：10一般委托；20专任委托
            string strKey = context.Request["keywords"];//房屋地址
            string strBeginTime = context.Request["stime"];//委托开始时间
            string strEndTime = context.Request["etime"];//委托开始时间
            string strOrderField = context.Request["orderfield"];

            Guid cityId = (string.IsNullOrEmpty(context.Request["cityid"])) ? Guid.Empty : new Guid(context.Request["cityid"]);
            Guid companyId = (string.IsNullOrEmpty(context.Request["companyid"])) ? Guid.Empty : new Guid(context.Request["companyid"]);
            Guid areaId = (string.IsNullOrEmpty(context.Request["areaid"])) ? Guid.Empty : new Guid(context.Request["areaid"]);
            Guid departId = (string.IsNullOrEmpty(context.Request["departid"])) ? Guid.Empty : new Guid(context.Request["departid"]);
            Guid userId = (string.IsNullOrEmpty(context.Request["userid"])) ? Guid.Empty : new Guid(context.Request["userid"]);

            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            
            if (userId != Guid.Empty)
                sb.AppendFormat(" AND (OperatorId = '{0}') ", userId);
            else if (departId != Guid.Empty)
                sb.AppendFormat(" AND (OptDepartId = '{0}')", departId);
            else if (areaId != Guid.Empty)
            {
                Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo item = null;
                string strCachkey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_DEPARTMENT, areaId);
                Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
                item = cs.GetObject<Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo>(strCachkey);
                if (!cs.Hit)
                {
                    item = Chenxin.Lib.Hr.DAL.Hr_DepartmentInfo.GetModel(areaId);
                    if (item != null) cs.Set(strCachkey, item, DateTime.Now.AddDays(1));
                }

                //hejifeng 100422 Modify
                //if (item == null) return string.Format("{{success:'0',msg:'{0}',data:''}}", "获取商圈或分类数据丢失");
                if (item == null) return retExecResult(Constants.ExecResult.Error, "获取商圈或分类数据丢失", "");
                
                sb.AppendFormat(" AND (OptDepartId in (select departId from v_Hr_DepartmentInfo where DepartSrc like '{0}%'))", item.DepartSrc);
            }
            else if (companyId != Guid.Empty)
                sb.AppendFormat(" AND (OptDepartId in (Select DepartId from v_Hr_DepartmentInfo where CompanyId = '{0}'))", companyId);
            else if (cityId != Guid.Empty)
                sb.AppendFormat(" AND (OptDepartId in (Select DepartId from v_Hr_DepartmentInfo where CityId = '{0}'))", cityId);
            else 
                sb.AppendFormat(" AND (OptDepartId in (Select DepartId from v_Hr_DepartmentInfo where CompanyId = '{0}'))", CurrentUserInfo.CompanyId);
           
            if (!string.IsNullOrEmpty(strRegion)) sb.AppendFormat(" AND (District = '{0}')", strRegion);
            
            if (iStatus != 1000) sb.AppendFormat(" AND (Status = {0})", iStatus);
            if (iBussines != 1000) sb.AppendFormat(" AND (EntrustType = {0})", iBussines);
            if (iTrustType != 1000) sb.AppendFormat(" AND (Type = {0})", iTrustType);

            if (!string.IsNullOrEmpty(strKey)) sb.AppendFormat(" AND ((HouseAddress like '%{0}%') OR (HouseCode Like '%{0}%') OR (EntrustCode LIKE '%{0}%') )", strKey);
            if (!string.IsNullOrEmpty(strBeginTime)) sb.AppendFormat(" AND (StartTime >= '{0}')", strBeginTime);
            if (!string.IsNullOrEmpty(strEndTime)) sb.AppendFormat(" AND (EndTime < '{0}')", DateTime.Parse(strEndTime).AddDays(1));
            

            System.Text.StringBuilder sbOrder = new System.Text.StringBuilder();
            if (!string.IsNullOrEmpty(strOrderField))
            {
                sbOrder.AppendFormat(" Order By {0}", strOrderField);
            }
            else
            {
                sbOrder.Append(" InputTime DESC");
            }

            //判断权限范围/////////////////////////////////////////////
            System.Text.StringBuilder sb2 = new System.Text.StringBuilder();
            //string strPermitCode0 = "entrust.view.all";//查看所有委托
            //string strPermitCode1 = "entrust.view.depart";//查看部门委托

            sb2.Append(" (1=1) ");

            //所有委托
            if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewAllEntrust))
            {
            }
            //城市级委托
            else if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewCityEntrust))
            {
                sb2.AppendFormat(" AND (CityId = '{0}') ", CurrentUserInfo.CityId);
            }
            //公司级委托
            else if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewCompanyEntrust))
            {
                sb2.AppendFormat(" AND (OptCompanyId = '{0}') ", CurrentUserInfo.CompanyId);
            }
            //部门级委托
            else if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewDepartEntrust))
            {
                sb2.Append("and (EXISTS(");
                sb2.Append("Select 1 from v_Struct_UserDepartRelation M ");
                sb2.AppendFormat("WHERE (House_EntrustInfo.OptDepartId = M.Departid AND  M.Userid= '{0}' AND ViewEntrust = 1) ", CurrentUserInfo.UserId);
                sb2.Append("))");
            }
            else
            {
                sb2.AppendFormat(" AND (OperatorId = '{0}') ", CurrentUserInfo.UserId);
            }

            if (sb.ToString().Trim() != "") sb2.Append(sb);

            string fieldlist = " EntrustId, HouseId, HouseAddress, EntrustCode, Employee, EmpDepart, PropertyCode, " +
                "InputTime, StartTime, EndTime, CustomerId, CustomerName, Phone, Mobile, District, TotalPrice, EntrustType, " +
                "Area, Status, Type, RentPrice, Operator, OptDepart, OptCompanyId, OptCompany, EmployeeId, EmpDepartId, HasApply, " +
                "HouseCode, OperatorId, OptDepartId";

            string tablefieldlist = " EntrustId, HouseId, HouseAddress, EntrustCode, Employee, EmpDepart, PropertyCode, " +
                "InputTime, StartTime, EndTime, CustomerId, CustomerName, Phone, Mobile, District, TotalPrice, EntrustType, " +
                "Area, Status, Type, RentPrice, Operator, OptDepart, OptCompanyId, OptCompany, EmployeeId, EmpDepartId, HasApply, " +
                "HouseCode, OperatorId, OptDepartId";

            
            System.Data.DataSet dslist = Chenxin.Lib.House.DAL.House_EntrustInfo.GetList(
                iPageIndex, iPageSize, sbOrder.ToString(), "House_EntrustInfo", sb2.ToString(), fieldlist, tablefieldlist, true);

            int count = (int)dslist.Tables[1].Rows[0][0];

            string strHtml = "";
            if (!GetEntrustListHtml(dslist, out strHtml))
            {
                //hejifeng 100422 Modify
                //return string.Format("{{success:'0',msg:'{0}',data:''}}", "生成HTML错误");
                return retExecResult(Constants.ExecResult.Error, "生成HTML错误", "");
            }

            dslist.Dispose();
            dslist = null;
            //hejifeng 100422 Modify
            //return string.Format("{{success:'1',msg:'{0}',data:{{count:'{1}',data:'{2}'}}}}", "成功", count, strHtml);
            Constants.Pagination stuPg = new Constants.Pagination();
            stuPg.count = count;
            stuPg.data = strHtml;

            return retExecResult(Constants.ExecResult.Succ, "成功", stuPg);
        }
        catch (Exception ex)
        {
            return retExecResult(Constants.ExecResult.Error, "生成HTML错误:" + ex.Message, "");
        }
    }

    private bool GetEntrustListHtml(System.Data.DataSet dslist, out string strHtml)
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        sb.Append("<table width=\"100%\" height=\"100%\" cellspacing=\"1\" class=\"tabsorternew\" id=\"report\">");
        sb.Append("<thead>");
        sb.Append("<tr><th style=\"width:55px\">操作</th>");
        sb.Append("<th>区域</th><th>地址</th>");
        sb.Append("<th>委托编号</th>");
        sb.Append("<th>面积</th><th>总价（万）</th>");
        sb.Append("<th>租价</th><th>部门</th>");
        sb.Append("<th>业务员</th><th>委托时间</th>");
        sb.Append("</tr></thead>");
        sb.Append("<tbody>");

        int i = 0;
        foreach (System.Data.DataRow row in dslist.Tables[0].Rows)
        {
            if (i%2 == 0)
                sb.AppendFormat("<tr id=\"{0}\" class=\"tr_houselist\">", row["EntrustId"].ToString());
            else
                sb.AppendFormat("<tr id=\"{0}\" class=\"tr_houselist bluebgcolor\">", row["EntrustId"].ToString());

            //操作列
            sb.AppendFormat("<td>{0} {1}<br/>{2} {3}</td>", 
                string.Format("<a name=\"{0}\" class=\"a_commission_view\" href=\"javascript:void(0)\">查看</a>", row["EntrustId"].ToString()),
                string.Format("<a name=\"{0}\" class=\"a_commission_edit\" href=\"javascript:void(0)\">修改</a>", row["EntrustId"].ToString()),
                string.Format("<a name=\"{0}\" class=\"a_commission_del\" href=\"javascript:void(0)\">删除</a>", row["EntrustId"].ToString()),
                (DatasetHelper.GetValue(row, "Status", 0) == 0) ? 
                string.Format("<a name=\"{0}\" class=\"a_commission_invalid\" href=\"javascript:void(0)\">作废</a>", row["EntrustId"].ToString()) :
                string.Format("<a name=\"{0}\" class=\"a_commission_resume\" href=\"javascript:void(0)\">恢复</a>", row["EntrustId"].ToString()));

            //区域列
            sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "District", ""));

            //地址列
            sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "HouseAddress", ""));

            //委托编号
            sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "EntrustCode", ""));

            //委托类型
            //sb.AppendFormat("<td>{0}</td>", (Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "Type", 0) == 10) ? "一般委托":"专任委托");

            //面积
            sb.AppendFormat("<td>{0:f2}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "Area", 0));

            //总价
            sb.AppendFormat("<td>{0:f0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "TotalPrice", 0.00)/10000);
            //租价
            sb.AppendFormat("<td>{0:f0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "RentPrice", 0));
            //部门
            sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "EmpDepart", ""));
            //业务员
            sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "Employee", ""));
            //跟盘时间
            sb.AppendFormat("<td>{0:yyyy-MM-dd} 至 </br>{1:yyyy-MM-dd}</td>", 
                Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "StartTime", DateTime.Today),
                Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "EndTime", DateTime.Today));

            sb.Append("</tr>");

            i++;
        }

        sb.Append("</tbody></table>");

        strHtml = sb.ToString();
        return true;
    }
    
    
    /// <summary>
    /// 
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    private string GetEntrustModel(HttpContext context)
    {
        Guid modelId = (string.IsNullOrEmpty(context.Request["modelid"])) ? Guid.Empty : new Guid(context.Request["modelid"]);

        if (modelId == Guid.Empty) return string.Format("{{success:'0',msg:'{0}',data:{{}}}}", "委托标识丢失，请联系管理员！");
        Chenxin.Lib.House.Entity.House_EntrustInfo model = null;
        
        //从缓存中获取
        Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.HOUSE);
        string strCachKey = string.Format(Chenxin.Lib.Cache.CacheDataType.HOUSE_ENTRUST, modelId);
        model = cs.GetObject<Chenxin.Lib.House.Entity.House_EntrustInfo>(strCachKey);

        if (!cs.Hit)
        {
            model = Chenxin.Lib.House.DAL.House_EntrustInfo.GetModel(modelId);
            if (model != null) cs.Set(strCachKey, model, DateTime.Now.AddDays(1));
        }
        
        if (model == null) return string.Format("{{success:'0',msg:'{0}',data:{{}}}}", "委托记录不存在，或记录标识错误！");
        
        return string.Format("{{success:'1',msg:'成功',data:{{model:{0}}}}}",
                Chenxin.Lib.Utility.JsonHelp.Convert2Json(model));
    }
    
    /// <summary>
    /// 添加委托信息
    /// </summary>
    /// <param name="context">参数为实体转换的Json</param>
    /// <returns></returns>
    private string AddEnTrustInfo(HttpContext context)
    {
        try
        {
            Chenxin.Lib.House.Entity.House_EntrustInfo model = (Chenxin.Lib.House.Entity.House_EntrustInfo)Chenxin.Lib.Utility.JsonHelp.Convert2Entity(context.Request["model"], typeof(Chenxin.Lib.House.Entity.House_EntrustInfo));

            if (model.HouseId == null) return string.Format("{{success:'0',msg:'{0}',data:{{}}}}", "房源标识丢失，请联系管理员！");
            if (string.IsNullOrEmpty(model.EntrustCode)) return string.Format("{{success:'0',msg:'{0}',data:{{}}}}", "委托编号丢失，请联系管理员！");

            //if (!GetEntrustCode(model.EntrustCode.Trim(), model.EntrustType, model.Type, model.EmpDepartId, out code))
            //{
            //    return string.Format("{{success:'0',msg:'{0}',data:{{}}}}", code);
            //}

            Chenxin.Lib.Passport.Entity.Hr_UserInfo user = Chenxin.Lib.Passport.DAL.Hr_UserInfo.GetEntityById(model.EmployeeId);
            if (user==null)
            {
                return string.Format("{{success:'0',msg:'{0}',data:{{}}}}", "委托人员不存在，请联系管理员！");
            }
            //对非表单项目进行处理
            //model.EntrustCode = code;
            model.CityId = user.CityId;
            model.Operator = user.UserName;
            model.OperatorId = user.UserId;
            model.OptDepart = user.DepartName;
            model.OptDepartId = user.DepartId;
            model.OptCompany = user.CompanyName;
            model.OptCompanyId = user.CompanyId;
            model.EntrustId = Guid.NewGuid();
            model.HasApply = false;
            model.InputTime = DateTime.Now;
            model.CustomerId = Guid.NewGuid();
            model.Status = 0;

            //添加委托
            Chenxin.Lib.House.DAL.House_EntrustInfo.Add(model);
            
            //添加委托客户
            Chenxin.Lib.House.Entity.Customer_BaseInfo customer_BaseInfo = new Chenxin.Lib.House.Entity.Customer_BaseInfo();
            customer_BaseInfo.CustomerId = model.CustomerId;
            customer_BaseInfo.CustomerCode = Chenxin.Lib.House.DAL.Customer_BaseInfo.GetCustomerCode(model.OperatorId);
            customer_BaseInfo.CustomerName = model.CustomerName;
            customer_BaseInfo.Address = model.CustomerAddress;
            customer_BaseInfo.Mobile = model.Mobile;
            customer_BaseInfo.Phone = model.Phone;
            customer_BaseInfo.Nationality = model.Nationality;
            customer_BaseInfo.CompanyId = model.OptCompanyId;
            customer_BaseInfo.CompanyName = model.OptCompany;

            customer_BaseInfo.Status = 0;
            customer_BaseInfo.CustomerKind = 50;	
            customer_BaseInfo.Adddate = DateTime.Now;
            customer_BaseInfo.AddPersonId = user.UserId;
            customer_BaseInfo.AddPerson = user.UserName;
            customer_BaseInfo.AddDepartId = user.DepartId;
            customer_BaseInfo.AddDepart = user.DepartName;
            customer_BaseInfo.OprPersonId = user.UserId;
            customer_BaseInfo.OprPerson = user.UserName;
            customer_BaseInfo.OprDepartId = user.DepartId;
            customer_BaseInfo.OprDepart = user.DepartName;
            customer_BaseInfo.CompanyId = user.CompanyId;
            customer_BaseInfo.CompanyName = user.CompanyName;
            customer_BaseInfo.CityId = user.CityId;
            customer_BaseInfo.CityName = user.CityName;
            customer_BaseInfo.LastTraceDay = DateTime.Now;
            customer_BaseInfo.PubLevel = 0;
            
            Chenxin.Lib.House.DAL.Customer_BaseInfo.Add(customer_BaseInfo);

            //添加跟单记录
            Chenxin.Lib.House.Entity.House_TraceInfo house_TraceInfo = new Chenxin.Lib.House.Entity.House_TraceInfo();
            //跟单方式	
            house_TraceInfo.TraceType = 0;
            //跟单内容	 
            house_TraceInfo.TraceContext = "房源已设置委托,编号:" + model.EntrustCode;
            //房源Id	 
            house_TraceInfo.HouseId = model.HouseId;
            //房源编号	
            house_TraceInfo.HouseCode = model.HouseCode;
            //房源地址	 
            house_TraceInfo.HouseAddress = model.HouseAddress;
            house_TraceInfo.status = 0;
            
            //更新房源表
            Chenxin.Lib.House.Entity.House_BaseInfo house_BaseInfo = Chenxin.Lib.House.DAL.House_BaseInfo.GetModel(model.HouseId);
            if (house_BaseInfo != null)
            {
                house_BaseInfo.IsTrust = true;
                house_BaseInfo.UpdateTime = DateTime.Now;
                house_BaseInfo.ServiceTime = DateTime.Now;
                Chenxin.Lib.House.DAL.House_BaseInfo.Update(house_BaseInfo);
            }

            //清除缓存
            string strCachKey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_HOUSEINFO, house_BaseInfo.HouseId);
            Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
            cs.Delete(strCachKey);

            house_TraceInfo.OprDepart = house_BaseInfo.OprDepart;
            house_TraceInfo.OprDepartId = house_BaseInfo.OprDepartId;
            house_TraceInfo.OprPerson = house_BaseInfo.OprPerson;
            house_TraceInfo.OprPersonId = house_BaseInfo.OprPersonId;

            AddTrace(house_TraceInfo);
            //添加用户操作日志 2010-5-11 王玮 Add
            AddLog("" + CurrentUserInfo.UserName + "添加了一个委托:[" + model.HouseAddress + "]房源已设置委托。",
                    OperationType.OperationTypeComboList()["OprType_TrustAdd"].ToString());
            
            return string.Format("{{success:'1',msg:'{0}',data:{{}}}}", "添加成功");
        }
        catch (Exception ex)
        {
            return string.Format("{{success:'0',msg:'意外错误：{0}',data:{{}}}}", ex.Message);
        }
    }

    private bool GetEntrustCode(string strInputCode, string businesstype, string trusttype, Guid departId, out string code)
    {
        code = "";
        if (trusttype == "10")//一般委托
        {
            code = strInputCode.PadLeft(8, '0');
        }
        else//专任委托
        {
            Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo hr_DepartmentInfo = Chenxin.Lib.Hr.DAL.Hr_DepartmentInfo.GetModel(departId);
            string hearder = "";
            if (hr_DepartmentInfo != null)
            {
                if ("10".Equals(businesstype))
                {
                    hearder = "C";
                }
                else
                {
                    hearder = "M";
                }
                code = hearder + hr_DepartmentInfo.DepartCode.Trim() + strInputCode.PadLeft(6, '0'); 
            }
        }

        //判断唯一
        if (!string.IsNullOrEmpty(code))
        {
            string strWhere = string.Format("EntrustCode = '{0}'", code);
            System.Collections.Generic.List<Chenxin.Lib.House.Entity.House_EntrustInfo> house_EntrustInfo = Chenxin.Lib.House.DAL.House_EntrustInfo.GetListArray(strWhere);
            if (house_EntrustInfo.Count > 0)
            {
                code = "委托编号已存在！";
                return false;
            }
        }

        return true;
    }

    /// <summary>
    /// 修改委托
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    private string EditEnTrustInfo(HttpContext context)
    {
        try
        {
            Chenxin.Lib.House.Entity.House_EntrustInfo model = (Chenxin.Lib.House.Entity.House_EntrustInfo)Chenxin.Lib.Utility.JsonHelp.Convert2Entity(context.Request["model"], typeof(Chenxin.Lib.House.Entity.House_EntrustInfo));

            //hejifeng 100422 Modify
            //if (model.EntrustId == null) return string.Format("{{success:'0',msg:'{0}',data:{{}}}}", "委托标识丢失，请联系管理员！");
            //if (model.HouseId == null) return string.Format("{{success:'0',msg:'{0}',data:{{}}}}", "房源标识丢失，请联系管理员！");
            //if (string.IsNullOrEmpty(model.EntrustCode)) return string.Format("{{success:'0',msg:'{0}',data:{{}}}}", "委托编号丢失，请联系管理员！");

            if (model.EntrustId == null) return retExecResult(Constants.ExecResult.Error, "委托标识丢失，请联系管理员！", "");
            if (model.HouseId == null) return retExecResult(Constants.ExecResult.Error, "房源标识丢失，请联系管理员！", "");
            if (string.IsNullOrEmpty(model.EntrustCode)) return retExecResult(Constants.ExecResult.Error, "委托编号丢失，请联系管理员！", "");
            
            //string code = "";
            //if (!GetEntrustCode(model.EntrustCode.Trim(), model.EntrustType, model.Type, model.EmpDepartId, out code))
            //{
            //    return string.Format("{{success:'0',msg:'{0}',data:{{}}}}", code);
            //}

            ////对非表单项目进行处理
            //model.EntrustCode = code;

            Chenxin.Lib.Passport.Entity.Hr_UserInfo user = Chenxin.Lib.Passport.DAL.Hr_UserInfo.GetEntityById(model.OperatorId);
            if (user == null)
            {
                return string.Format("{{success:'0',msg:'{0}',data:{{}}}}", "委托人员不存在，请联系管理员！");
            }
            //归属人
            model.CityId = user.CityId;
            model.Operator = user.UserName;
            model.OperatorId = user.UserId;
            model.OptDepart = user.DepartName;
            model.OptDepartId = user.DepartId;
            model.OptCompany = user.CompanyName;
            model.OptCompanyId = user.CompanyId;

            //更新委托
            Chenxin.Lib.House.DAL.House_EntrustInfo.Update(model);
            
            //重新设置缓存
            Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.HOUSE);
            string strCachKey = string.Format(Chenxin.Lib.Cache.CacheDataType.HOUSE_ENTRUST, model.EntrustId);
            cs.Set(strCachKey, model, DateTime.Now.AddDays(1));

            //修改委托客户
            Chenxin.Lib.House.Entity.Customer_BaseInfo customer_BaseInfo = Chenxin.Lib.House.DAL.Customer_BaseInfo.GetModel(model.CustomerId);
            customer_BaseInfo.CustomerId = model.CustomerId;
            customer_BaseInfo.CustomerName = model.CustomerName;
            customer_BaseInfo.Address = model.CustomerAddress;
            customer_BaseInfo.Mobile = model.Mobile;
            customer_BaseInfo.Phone = model.Phone;
            customer_BaseInfo.Nationality = model.Nationality;

            customer_BaseInfo.OprPersonId = user.UserId;
            customer_BaseInfo.OprPerson = user.UserName;
            customer_BaseInfo.OprDepartId = user.DepartId;
            customer_BaseInfo.OprDepart = user.DepartName;
            customer_BaseInfo.CompanyId = user.CompanyId;
            customer_BaseInfo.CompanyName = user.CompanyName;
            
            Chenxin.Lib.House.DAL.Customer_BaseInfo.Update(customer_BaseInfo);

            //hejifeng 100422 Modify
            //return string.Format("{{success:'1',msg:'{0}',data:{{}}}}", "更新成功");
            
            //添加用户操作日志 2010-5-11 王玮 Add
            AddLog("" + CurrentUserInfo.UserName + "修改了一个委托:[" + model.HouseAddress + "]房源修改了委托。",
                    OperationType.OperationTypeComboList()["OprType_TrustEdit"].ToString());
            
            return retExecResult(Constants.ExecResult.Succ, "更新成功", "");
        }
        catch (Exception ex)
        {
            //hejifeng 100422 Modify
            //return string.Format("{{success:'0',msg:'意外错误：{0}',data:{{}}}}", ex.Message);
            return retExecResult(Constants.ExecResult.Error, "意外错误：" + ex.Message, "");
        }
    }

    /// <summary>
    /// 作废委托
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    private string CancelEnTrustInfo(HttpContext context)
    {
        Guid entrustId = (string.IsNullOrEmpty(context.Request["entrustid"])) ? Guid.Empty : new Guid(context.Request["entrustid"]);

        if (entrustId == Guid.Empty) return string.Format("{{success:'0',msg:'{0}',data:{{}}}}", "委托标识丢失，请联系管理员");

        //作废委托
        Chenxin.Lib.House.DAL.House_EntrustInfo.CancelEntrustInfo(entrustId);
        
        //删除缓存
        Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.HOUSE);
        string strCachKey = string.Format(Chenxin.Lib.Cache.CacheDataType.HOUSE_ENTRUST, entrustId);

        Chenxin.Lib.House.Entity.House_EntrustInfo model = cs.GetObject<Chenxin.Lib.House.Entity.House_EntrustInfo>(strCachKey);

        if (!cs.Hit)
        {
            model = Chenxin.Lib.House.DAL.House_EntrustInfo.GetModel(entrustId);
            if (model != null) cs.Set(strCachKey, model, DateTime.Now.AddDays(1));
        }
        /*
        //添加跟单记录
        Chenxin.Lib.House.Entity.House_TraceInfo house_TraceInfo = new Chenxin.Lib.House.Entity.House_TraceInfo();
        //跟单方式	
        house_TraceInfo.TraceType = 0;
        //跟单内容	 
        house_TraceInfo.TraceContext = "作废了委托信息,编号:" + model.EntrustCode;
        //房源Id	 
        house_TraceInfo.HouseId = model.HouseId;
        //房源编号	
        house_TraceInfo.HouseCode = model.HouseCode;
        //房源地址	 
        house_TraceInfo.HouseAddress = model.HouseAddress;
        house_TraceInfo.status = 0;
        //添加用户跟单 2010-5-18 王玮 Add
        AddTrace(house_TraceInfo);
        */
        //添加用户操作日志 2010-5-11 王玮 Add
        AddLog("" + CurrentUserInfo.UserName + "作废了一个委托:[" + model.HouseAddress + "]房源作废了委托：" + model.EntrustCode+"",
                OperationType.OperationTypeComboList()["OprType_TrustCel"].ToString());
        
        return string.Format("{{success:'1',msg:'{0}',data:{{}}}}", "提交成功");
    }

    /// <summary>
    /// 取消作废
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    private string UncancelEnTrustInfo(HttpContext context)
    {
        Guid entrustId = (string.IsNullOrEmpty(context.Request["entrustid"])) ? Guid.Empty : new Guid(context.Request["entrustid"]);

        if (entrustId == Guid.Empty) return string.Format("{{success:'0',msg:'{0}',data:{{}}}}", "委托标识丢失，请联系管理员");

        //作废委托
        Chenxin.Lib.House.DAL.House_EntrustInfo.RestoreEntrustInfo(entrustId);

        //删除缓存
        Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.HOUSE);
        string strCachKey = string.Format(Chenxin.Lib.Cache.CacheDataType.HOUSE_ENTRUST, entrustId);

        Chenxin.Lib.House.Entity.House_EntrustInfo model = cs.GetObject<Chenxin.Lib.House.Entity.House_EntrustInfo>(strCachKey);

        if (!cs.Hit)
        {
            model = Chenxin.Lib.House.DAL.House_EntrustInfo.GetModel(entrustId);
            if (model != null) cs.Set(strCachKey, model, DateTime.Now.AddDays(1));
        }
        /*
        //添加跟单记录
        Chenxin.Lib.House.Entity.House_TraceInfo house_TraceInfo = new Chenxin.Lib.House.Entity.House_TraceInfo();
        //跟单方式	
        house_TraceInfo.TraceType = 0;
        //跟单内容	 
        house_TraceInfo.TraceContext = "恢复了委托信息,编号:" + model.EntrustCode;
        //房源Id	 
        house_TraceInfo.HouseId = model.HouseId;
        //房源编号	
        house_TraceInfo.HouseCode = model.HouseCode;
        //房源地址	 
        house_TraceInfo.HouseAddress = model.HouseAddress;
        house_TraceInfo.status = 0;
        //添加用户跟单 2010-5-18 王玮 Add
        AddTrace(house_TraceInfo);
        */
        //添加用户操作日志 2010-5-11 王玮 Add
        AddLog("" + CurrentUserInfo.UserName + "恢复了一个委托:[" + model.HouseAddress + "]房源恢复了委托：" + model.EntrustCode + "",
                OperationType.OperationTypeComboList()["OprType_TrustUnCel"].ToString());
        
        return string.Format("{{success:'1',msg:'{0}',data:{{}}}}", "提交成功");
    }

    private string ExistsCode(HttpContext context)
    {
        string strRet;
        try
        {
            string strEntrustCode = context.Request.Params["EntrustCode"];

            string strWhere = string.Format("EntrustCode = '{0}' and OptCompanyId='{1}'", strEntrustCode,CurrentUserInfo.CompanyId);
            System.Collections.Generic.List<Chenxin.Lib.House.Entity.House_EntrustInfo> lsEntrustInfo = Chenxin.Lib.House.DAL.House_EntrustInfo.GetListArray(strWhere);
            if (lsEntrustInfo.Count > 0)
            {
                strRet = retExecResult(Constants.ExecResult.Succ, "", true);
            }
            else
            {
                strRet = retExecResult(Constants.ExecResult.Succ, "", false);
            }
            return strRet;

        }
        catch (Exception ex)
        {
            strRet = retExecResult(Constants.ExecResult.Error, ex.Message, "");
            return strRet;
        }
    }

    //返回值説明     ：响应字符串
    //功能詳細       ：某一房屋对应委托信息
    //作成者         ：hejifeng
    //作成日         ：2010-04-29
    //修改者         ：
    //修改日         ：
    //*******************************************
    private string getHouseTrustList(HttpContext context)
    {
        string strRet;
        try
        {
            string houseid = context.Request.Params["houseid"];
            int PageIndex = 1;
            int PageSize = 10;

            //页码        
            if (!string.IsNullOrEmpty(context.Request.Params["pageindex"]))
            {
                PageIndex = int.Parse(context.Request.Params["pageindex"]) + 1;
            }
            //页显示行数
            if (!string.IsNullOrEmpty(context.Request.Params["pagesize"]))
            {
                PageSize = int.Parse(context.Request.Params["pagesize"]);
            }

            string OrderField = "House_EntrustInfo.InputTime desc";
            string StrWhere = string.Format("HouseId='{0}' and Status = 0", houseid);
            string FieldList = "Employee,EmpDepart,EntrustType,StartTime,EndTime,[Type],EntrustCode";
            string TableFieldList = "Employee,EmpDepart,EntrustType,convert(nvarchar(12),StartTime,111) as StartTime,convert(nvarchar(12),EndTime,111) as EndTime,case when Type='10' then '出售' when Type='20' then '出租' else '租售' end as [Type],EntrustCode";
            string TableName = "House_EntrustInfo";

            DataSet ds = null;
            if (PageIndex == 1)
            {
                Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.HOUSE);
                string strCachKey = string.Format(Chenxin.Lib.Cache.CacheDataType.HOUSE_INFO_TRUST, houseid);
                ds = cs.GetDataSet(strCachKey);

                if (!cs.Hit)
                {
                    ds = Chenxin.Lib.House.DAL.House_EntrustInfo.GetList(PageIndex, PageSize, OrderField, TableName, StrWhere, FieldList, TableFieldList, true);
                    if (ds != null) 
                        cs.Set(strCachKey, ds, DateTime.Now.AddMinutes(5));
                }
            }
            else
            {

                ds = Chenxin.Lib.House.DAL.House_EntrustInfo.GetList(PageIndex, PageSize, OrderField, TableName, StrWhere, FieldList, TableFieldList, true);
            }
            
            strRet = retExecResult(Constants.ExecResult.Succ, "", retPagination(ds));
            return strRet;
        }
        catch (Exception ex)
        {
            strRet = retExecResult(Constants.ExecResult.Error, ex.Message, "");
            return strRet;
        }
    }

    //生成html
    private Constants.Pagination retPagination(DataSet ds)
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();

        sb.Append("<table id=\"showWeiTou\" width=\"100%\" border=\"0\" align=\"center\" cellpadding=\"0\" cellspacing=\"0\"><thead>");
        sb.Append("<tr class=\"tab_line4\"><td width=\"30%\"><b>委托人</b></td><td width=\"10%\"><b>委托类型</b></td><td width=\"20%\"><b>有效期</b></td></td><td width=\"10%\"><b>委托性质</b></td><td width=\"22%\"><b>委托编号</b></td></tr>");
        foreach (DataRow dr in ds.Tables[0].Rows)
        {
            sb.AppendFormat("<tr class=\"tab_line5\"><td  title=\"{0}/{1}\">{0}/{1}</td><td  title=\"{2}\">{2}</td><td  title=\"{3}-{4}\">{3}-{4}</td><td  title=\"{5}\">{5}</td><td  title=\"{6}\">{6}</td></tr>", dr[0], dr[1], dr[2], dr[3], dr[4], dr[5], dr[6]);
        }
        sb.Append("</thead></table>");

        Constants.Pagination stuPag = new Constants.Pagination();
        stuPag.count = Convert.ToInt32(ds.Tables[1].Rows[0][0]);
        stuPag.data = sb.ToString();

        return stuPag;
    }

    //*******************************************
    //功能概要       ：响应字符串
    //参数説明       ：strMsg 消息 
    //返回值説明     ：void
    //功能詳細       ：权限检查
    //作成者         ：chen.yugong 
    //作成日         ：2010-05-20
    //修改者         ：
    //修改日         ：
    //*******************************************
    public override bool CustomerCheckPermint(HttpContext context, out string strMsg)
    {
        if (context.Request["op"] != null)
        {
            string op = context.Request["op"].ToLower();
            //实体变量
            Chenxin.Lib.House.Entity.House_EntrustInfo model = null;
            //传递参数用
            System.Collections.Hashtable per = new System.Collections.Hashtable();
            System.Collections.Hashtable confine = new System.Collections.Hashtable();
            //判断op参数
            if ((op.Equals("checkpermit") && ("edit".Equals(context.Request["code"]))) || "del".Equals(op) || "cancel".Equals(op) || "uncancel".Equals(op))
            {
                string id = null;

                //删除
                if ("del".Equals(op))
                {
                    id = context.Request["modelid"];
                    model = Chenxin.Lib.House.DAL.House_EntrustInfo.GetModel(new Guid(id));
                    if (model == null)
                    {
                        strMsg = "{success:0,msg:'委托信息获取失败！',data:''}";
                        return false;
                    }
                    //加如权限项
                    per.Add("ALL", Constants.Permit_DelTrust_All);
                    per.Add("CITY", Constants.Permit_DelTrust_City);
                    per.Add("COMPANY", Constants.Permit_DelTrust_Company);
                    per.Add("DEPART", Constants.Permit_DelTrust_Department);
                    //加入范围
                    confine.Add("CityId", model.CityId);
                    confine.Add("CompanyId", model.OptCompanyId);
                    confine.Add("OperatorId", model.OperatorId);
                    //检查权限
                    return CheckPermint(per, confine, checkDepartPermit(model.OptDepartId, op), out strMsg);
                }
                //作废
                if ("cancel".Equals(op))
                {
                    id = context.Request["entrustid"];
                    model = Chenxin.Lib.House.DAL.House_EntrustInfo.GetModel(new Guid(id));
                    if (model == null)
                    {
                        strMsg = "{success:0,msg:'委托信息获取失败！',data:''}";
                        return false;
                    }
                    //加如权限项
                    per.Add("ALL", Constants.Permit_CancelTrust_All);
                    per.Add("CITY", Constants.Permit_CancelTrust_City);
                    per.Add("COMPANY", Constants.Permit_CancelTrust_Company);
                    per.Add("DEPART", Constants.Permit_CancelTrust_Department);
                    //加入范围
                    confine.Add("CityId", model.CityId);
                    confine.Add("CompanyId", model.OptCompanyId);
                    confine.Add("OperatorId", model.OperatorId);
                    //检查权限
                    return CheckPermint(per, confine, checkDepartPermit(model.OptDepartId, op), out strMsg);
                }
                //取消作废
                if ("uncancel".Equals(op))
                {
                    id = context.Request["entrustid"];
                    model = Chenxin.Lib.House.DAL.House_EntrustInfo.GetModel(new Guid(id));
                    if (model == null)
                    {
                        strMsg = "{success:0,msg:'委托信息获取失败！',data:''}";
                        return false;
                    }

                    //加如权限项
                    per.Add("ALL", Constants.Permit_UnCancelTrust_All);
                    per.Add("CITY", Constants.Permit_UnCancelTrust_City);
                    per.Add("COMPANY", Constants.Permit_UnCancelTrust_Company);
                    per.Add("DEPART", Constants.Permit_UnCancelTrust_Department);
                    //加入范围
                    confine.Add("CityId", model.CityId);
                    confine.Add("CompanyId", model.OptCompanyId);
                    confine.Add("OperatorId", model.OperatorId);
                    //检查权限
                    return CheckPermint(per, confine, checkDepartPermit(model.OptDepartId, op), out strMsg);
                }
                //编辑
                if (op.Equals("checkpermit") && "edit".Equals(context.Request["code"]))
                {
                    id = context.Request["currentId"];
                    model = Chenxin.Lib.House.DAL.House_EntrustInfo.GetModel(new Guid(id));
                    if (model == null)
                    {
                        strMsg = "{success:0,msg:'委托信息获取失败！',data:''}";
                        return false;
                    }
                    //加如权限项
                    per.Add("ALL", Constants.Permit_EditTrust_All);
                    per.Add("CITY", Constants.Permit_EditTrust_City);
                    per.Add("COMPANY", Constants.Permit_EditTrust_Company);
                    per.Add("DEPART", Constants.Permit_EditTrust_Department);
                    //加入范围
                    confine.Add("CityId", model.CityId);
                    confine.Add("CompanyId", model.OptCompanyId);
                    confine.Add("OperatorId", model.OperatorId);
                    //检查权限
                    return CheckPermint(per, confine, checkDepartPermit(model.OptDepartId, context.Request["code"]), out strMsg);
                }
            }
        }
        strMsg = "{success:1,msg:'',data:{permit:true}}";
        return true;
    }


    //*******************************************
    //功能概要       ：部门内有无封盘解盘权限
    //参数説明       ：context 上下文
    //返回值説明     ：bool
    //功能詳細       ：部门内有无封盘解盘权限
    //作成者         ：chen.yugong 
    //作成日         ：2010-05-19
    //修改者         ：
    //修改日         ：
    //*******************************************
    public bool checkDepartPermit(Guid departId, string op)
    {
        //检查有无权限
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        sb.AppendFormat(" (Departid = '{0}' AND  Userid= '{1}') ", departId, CurrentUserInfo.UserId);
        System.Collections.Generic.List<Chenxin.Lib.Hr.Entity.Struct_UserDepartRelation> list = Chenxin.Lib.Hr.DAL.Struct_UserDepartRelation.GetListArray(sb.ToString());
        if (list.Count > 0)
        {
            Chenxin.Lib.Hr.Entity.Struct_UserDepartRelation struct_UserDepartRelation = list[0];
            //作废委托
            if("cancel".Equals(op)) {
                return struct_UserDepartRelation.CanCancelTrust;
            }
            //取消作废
            if("uncancel".Equals(op)) {
                return struct_UserDepartRelation.UnCancelTrust;
            }
            //删除作废
            if("del".Equals(op)) {
                return struct_UserDepartRelation.CanDelTrust;
            }
            //编辑委托
            if ("edit".Equals(op))
            {
                return struct_UserDepartRelation.EditTrust;
            }
        } 
        return false;
    }
}